<?php

namespace app\schoolwall\controller;

use think\Controller;

//引入邮箱类
use app\common\library\Email as LibraryEmail;

class Code extends Controller
{
    protected $CodeModel = null;
    protected $User = null;

    protected function _initialize()
    {
        $this->CodeModel = model('common/User/Code');
        $this->User = model('common/User/User');
    }

    //发送验证码
    public function send()
    {
        if ($this->request->isPost()) {
            $email = $this->request->param('email', '', 'trim');
            $newemail = $this->request->param('newemail', '', 'trim');//修改邮箱时的新邮箱
            $type = $this->request->param('type', '', 'trim');

            if (empty($email)) {
                return $this->error('邮箱不能为空');
            }

            if(!empty($newemail)){
                $email = $newemail;
            }

            //每次邮箱发过来，都把三十分钟前的删除
            $this->CodeModel->whereTime('createtime', '<', '-30 minutes')->delete();

            $user = $this->User->where('email', $email)->find();

            if ($type === 'login' || $type === 'delete') {
                if (!$user) {
                    return $this->error('用户不存在');
                }
            } else {
                if ($user) {
                    return $this->error('该邮箱已被注册');
                }
            }

            //生成验证码
            $code = build_randstr(6);

            //开启事务
            $this->CodeModel->startTrans();

            //查询邮箱是否已经存在验证码
            $ems = $this->CodeModel->where('email', $email)->find();

            if ($ems) {
                $data = [
                    'id' => $ems['id'],
                    'code' => $code,
                    'times' => bcadd($ems['times'], 1,)
                ];

                if ($ems['times'] > 5 && $ems['ip'] === $this->request->ip()) {
                    //同一账号和ip发送验证次数太多
                    $this->error('验证码发送次数过多，请稍后再试');
                }

                $res = $this->CodeModel->validate('common/Schoolwall/Code.edit')->isUpdate(true)->save($data);
            } else {
                $data = [
                    'email' => $email,
                    'code' => $code,
                    'ip' => $this->request->ip(),
                    'times' => 1,
                ];

                $res = $this->CodeModel->validate('common/Schoolwall/Code')->save($data);
            }

            if ($res === false) {
                $this->error($this->CodeModel->getError() . '请稍后再试');
            }

            //实例化邮箱类
            $Mail = new LibraryEmail();

            //用户接受到的正文
            $html = "您的校园墙验证码为：<b>$code</b>";

            //获取发件人
            $FromEmail = config('site.mail_from');

            //发送邮件
            $SendStatus = $Mail->subject('校园墙平台认证')->from($FromEmail, '校园墙')->message($html)->to($email)->send();

            if ($SendStatus === false) {
                //事务回滚
                $this->CodeModel->rollback();

                $this->error($Mail->getError() . '验证码发送失败,请稍后再试');
            } else {
                //确认事务
                $this->CodeModel->commit();
                $this->success('验证码发送成功');
            }
        }
    }
}
